package com.example.guiguiapplicatio.DataManager;

import android.os.Handler;
import android.os.Looper;

import com.example.guiguiapplicatio.api.Interface.getServicepackCallback;
import com.example.guiguiapplicatio.Response.ServicePackageResponse;
import com.example.guiguiapplicatio.fragment.home.adapter.ServicepacksListAdapter;
import com.example.guiguiapplicatio.util.ResponseBody;

import java.lang.ref.WeakReference;
import java.util.List;

public class SelectServicePackageData implements getServicepackCallback {
    private WeakReference<ServicepacksListAdapter> adapterReference;

    public SelectServicePackageData(ServicepacksListAdapter adapter) {
        this.adapterReference = new WeakReference<>(adapter);
    }

    @Override
    public void onFailure(String errorMessage) {
        // Handle failure if needed
    }

    @Override
    public void getServicepackApionSuccess(ResponseBody<List<ServicePackageResponse>> dataResponseBody) {
        ServicepacksListAdapter adapter = adapterReference != null ? adapterReference.get() : null;
        if (adapterReference != null && adapterReference.get() != null) {
            List<ServicePackageResponse> data = dataResponseBody.getData();
            runOnUiThread(() -> {
                adapter.setData(data);
                adapter.notifyDataSetChanged();
            });
        }
    }
    public List<ServicePackageResponse> getSelectedItems() {
        ServicepacksListAdapter adapter = adapterReference != null ? adapterReference.get() : null;
        return adapter.getSelectedItems();
    }
    private void runOnUiThread(Runnable action) {
        // Check if we are already on the main thread
        if (Looper.myLooper() == Looper.getMainLooper()) {
            action.run();
        } else {
            // Use a Handler to post the action to the main thread's message queue
            Handler mainHandler = new Handler(Looper.getMainLooper());
            mainHandler.post(action);
        }
    }
}
